import dayjs from 'dayjs';
import { getExpireTimestamp } from '@/utils/day';

export const cache = {
  /**
   * 设置缓存
   * @param key 键
   * @param value 值
   * @param lifetime 有效期（1s、1m、1h、1d、1M 等）
   */
  set(key: string, value: any, lifetime: string): void {
    const expires = getExpireTimestamp(lifetime);
    const cacheItem = { value, expires };
    uni.setStorageSync(key, cacheItem);
  },

  /**
   * 获取缓存
   * @param key 键
   * @returns
   */
  get(key: string): any | undefined {
    try {
      const cacheItem = uni.getStorageSync(key);
      if (cacheItem && cacheItem.expires > dayjs().unix()) {
        return cacheItem.value;
      }

      // 删除已过期的缓存
      uni.removeStorageSync(key);
      return undefined;
    } catch (error) {
      console.error(`Error getting cache item for key ${key}:`, error);
      return undefined;
    }
  },

  /**
   * 删除缓存
   * @param key
   */
  del(key: string): void {
    uni.removeStorageSync(key);
  },
};
